package cn.shengongying.service.impl;

import cn.shengongying.dao.InformationMapper;
import cn.shengongying.model.Information;
import cn.shengongying.service.IInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户消息信息 服务实现类
 * </p>
 *
 * @author RXK
 * @since 2022-01-12
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements IInformationService {

    private final InformationMapper informationMapper;

    public InformationServiceImpl(InformationMapper informationMapper) {
        this.informationMapper = informationMapper;
    }

    @Override
    public int findByUserIdAndSourceIdAndDate(Long userId, Long sourceId, int type) {
        return informationMapper.findByUserIdAndSourceIdAndDate(userId, sourceId, type);
    }

    @Override
    public void save(List<Information> informationList) {
        informationMapper.save(informationList);
    }

    @Override
    public List<Information> findByUserIdAndType(Long userId, Integer type, Integer offset, Integer pageSize) {
        List<Information> list = informationMapper.findByUserIdAndType(userId, type, offset, pageSize);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Information> updates = list.stream()
                    .filter(information -> information.getRead() == 0)
                    .map(information -> {
                        Information update = new Information();
                        update.setId(information.getId());
                        update.setRead(1);
                        return update;
                    })
                    .collect(Collectors.toList());
            updateBatchById(updates);
        }
        return list;
    }

    @Override
    public Map<Integer, Integer> statistic(Long userId) {
        return informationMapper.statistic(userId);
    }

    @Override
    public void insert(Information information) {
        informationMapper.create(information);
    }
}
